<template>
  <el-card class="attr-table">
    <el-form>
      <el-form-item label="属性名">
        <el-input
          placeholder="请输入属性名"
          class="attr-input"
          v-model="attrFormData.attrName"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :icon="Plus"
          :disabled="!attrFormData.attrName"
          @click="showSaveAttrValue"
        >
          添加属性值
        </el-button>
        <el-table :data="attrFormData.attrValueList" border class="attr-table">
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="60"
          />
          <el-table-column label="属性值名称">
            <template v-slot="{ row, $index }">
              <!-- 
                input 编辑模式
                span  显示模式
              -->
              <el-input
                size="small"
                ref="inputRef"
                v-if="row.isEdit"
                v-model="row.valueName"
                @blur="addAttrValue(row, $index)"
                @keyup.enter="addAttrValue(row, $index)"
              />
              <span class="attr-value-text" v-else @click="showEdit(row)">
                {{ row.valueName }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template v-slot="{ row, $index }">
              <el-popconfirm
                :title="`您确认要删除 ${row.valueName} 吗?`"
                @confirm="delAttr($index)"
              >
                <template #reference>
                  <el-button type="danger" :icon="Delete" size="small" />
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <!-- 
          1. 必须有属性名 attrFormData.attrName
          2. 属性值至少有一个数据，数据要包含数据值名称 attrFormData.attrValueList
         -->
        <el-button
          type="primary"
          :disabled="isBtnDisabled"
          @click="saveOrUpdateAttr"
        >
          确定
        </el-button>
        <el-button @click="goAttrList">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "SaveOrUpdateAttr",
};
</script>

<script lang="ts" setup>
import { reactive, ref, nextTick, computed } from "vue";
import { Plus, Delete } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { saveOrUpdateAttrApi } from "@/api/product/attr";
import type {
  SaveAttrItem,
  SaveAttrValueItem,
} from "@/api/product/model/attrModel";
import { useCategoryStore } from "@/stores/category";

const props = defineProps<{
  attr: SaveAttrItem;
}>();

// 声明接受自定义事件
const emit = defineEmits(["setIsShowAttrList"]);
// 取消，跳转到AttrList组件
const goAttrList = () => {
  emit("setIsShowAttrList", true);
};
const categoryStore = useCategoryStore();
// 添加或更新属性
const saveOrUpdateAttr = async () => {
  await saveOrUpdateAttrApi({
    ...attrFormData,
    categoryId: categoryStore.category3Id as number,
    categoryLevel: 3,
  });
  ElMessage.success(`${attrFormData.id ? "修改" : "添加"}属性成功`);
  goAttrList();
};

const attrFormData = reactive<SaveAttrItem>(props.attr);

// 确定按钮是否禁用
const isBtnDisabled = computed(() => {
  return (
    !attrFormData.attrName ||
    !attrFormData.attrValueList.some((attrValue) => attrValue.valueName)
  );
});

const inputRef = ref();

// 显示添加属性值（table添加一行属性显示）
const showSaveAttrValue = async () => {
  // table添加一行属性显示
  attrFormData.attrValueList.push({
    // 决定显示和编辑模式
    isEdit: true,
    valueName: "",
  });

  // nextTick(() => {
  //   console.log(inputRef.value);
  // });

  /*
    简单理解：等DOM元素更新完成（用户界面渲染完成），再触发
    真正理解：将要执行的代码添加到异步队列（微任务）去等待执行

    const resolvedPromise = Promise.resolve();
    function nextTick(fn) {
      const p = currentFlushPromise || resolvedPromise;
      return fn ? p.then(this ? fn.bind(this) : fn) : p;
    }
  */
  await nextTick();
  // 让输入框聚焦
  inputRef.value.focus();
};

// 变成显示模式
const addAttrValue = (row: SaveAttrValueItem, index: number) => {
  // 判断是否输入内容
  if (!row.valueName) {
    // 没有内容，要删除当前行数据
    attrFormData.attrValueList.splice(index, 1);
    return;
  }
  // 有内容变成显示模式
  row.isEdit = false;
};
// 变成编辑模式
const showEdit = async (row: SaveAttrValueItem) => {
  row.isEdit = true;

  await nextTick();
  // 让输入框聚焦
  inputRef.value.focus();
};

// 删除属性
const delAttr = (index: number) => {
  attrFormData.attrValueList.splice(index, 1);
};
</script>

<style scoped>
.attr-input {
  width: 200px;
}
.attr-table {
  margin-top: 20px;
}

.attr-value-text {
  display: inline-block;
  width: 100%;
}
</style>
